package main

import (
	"context"
	"go2/log"
	pool "goroutine-pool"
	"net"
	proxy_handle "proxy/handle"
	"time"
)

func StartProxyServer(addr string) {
	// 创建带有超时配置的监听器
	config := &net.ListenConfig{
		KeepAlive: 3 * time.Minute,
	}

	listener, err := config.Listen(context.Background(), "tcp", addr)
	if err != nil {
		log.Error("Failed to start proxy server:", err)
		return
	}
	defer listener.Close()

	log.Info("Proxy server started on ", addr)
	log.Info("Supporting both HTTP and SOCKS5 protocols")

	// 创建协程池
	p := pool.NewPoolWithMaxPerCore(1024, 128)

	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Error("Accept error:", err)
			continue
		}

		// 提交任务
		p.Submit(&pool.Task{
			Name: conn.RemoteAddr().String(),
			Fn: func(ctx context.Context) error {
				defer func() {
					conn.Close()
				}()
				// 设置连接超时
				conn.SetDeadline(time.Now().Add(5 * time.Minute))
				proxy_handle.Serve(conn, conn.RemoteAddr().String())
				return nil
			},
			Config: pool.TaskConfig{
				CPUCore:  -1,                // 不绑定CPU
				Priority: pool.PriorityHigh, // 普通优先级
				Timeout:  0,                 // 无超时限制
			},
		})
	}
}

func main() {
	help()
	proxy_handle.Init()
	StartProxyServer(m_cli_proxy_addr)
}
